package com.iye.puretennis.fragment;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import com.iye.puretennis.R;
import com.iye.puretennis.domain.User;
import com.iye.puretennis.domain.UserToken;
import com.iye.puretennis.helper.Constant;
import com.iye.puretennis.helper.RemoteUrlCollections;
import com.iye.puretennis.helper.ServerAccessHelper;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Author: Chuanbao on 2014/11/19.
 */
public class MyFriendsFragment extends TabFragment {
    private View mMainView;
    private ListView friendsView;
    private ListView invitationsView;
    private List<User> friends = new ArrayList<User>();
    private List<FriendRequest> friendRequests = new ArrayList<FriendRequest>();

    private FriendsAdapter friendsAdapter;
    private FriendsRequestsAdapter friendsRequestsAdapter;

    private String friendsJson;
    private String friendsRequestsJson;

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mMainView = inflater.inflate(R.layout.myfriends, container, false);
        friendsView = (ListView) mMainView.findViewById(R.id.myfriends_list);
        invitationsView = (ListView) mMainView.findViewById(R.id.myfriends_invitation_list);

        UserToken userToken = dbManager.retrieveCurrentUser();
        friendsListRender(userToken);
        invitationsListRender(userToken);

        friendsAdapter = new FriendsAdapter(getActivity(),R.layout.myfriend_item);
        friendsRequestsAdapter = new FriendsRequestsAdapter(getActivity(),R.layout.myfriend_invitation_item);
        return mMainView;
    }

    @Override
    public void updateUI() {
        Toast.makeText(getActivity(),"To do my friends list update.",Toast.LENGTH_SHORT).show();
    }

    private class FriendsAdapter extends BaseAdapter {
        private int resource;//数据绑定在哪个资源界面上
        private LayoutInflater inflater;//布局填充器,可以使用xml文件来生成它的view对象
        private FriendItemViewCache viewCache;

        FriendsAdapter(Context context, int resource) {
            this.resource = resource;
            inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }

        @Override
        public int getCount() {
            return friends.size();
        }

        @Override
        public Object getItem(int position) {
            return friends.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            TextView nameView = null;
            ImageButton detailBtn = null;

            if(convertView == null){//第一次渲染页面
                convertView = inflater.inflate(resource,null);
                nameView = (TextView) convertView.findViewById(R.id.myfriend_item_name);
                detailBtn = (ImageButton) convertView.findViewById(R.id.myfriend_item_action_details);
                viewCache = new FriendItemViewCache();
                viewCache.nameTextView = nameView;
                viewCache.detailBtn = detailBtn;
                convertView.setTag(viewCache);
            }else{
                nameView = viewCache.nameTextView;
                detailBtn = viewCache.detailBtn;
            }
            User friend = friends.get(position);
            nameView.setText(friend.getName());
            detailBtn.setOnClickListener(new ButtonListener(position));
            return convertView;
        }

        private class ButtonListener implements View.OnClickListener{
            int position;

            public ButtonListener(int position) {
                this.position = position;
            }

            @Override
            public void onClick(View v) {
                User friend = friends.get(position);
                //TODO-- call remote server to show friend detail page
                Toast.makeText(getActivity(), "Friend details:" + friend.getName() + friend.getGuid(), Toast.LENGTH_SHORT).show();
            }
        }

        private class FriendItemViewCache{
            private TextView nameTextView;
            private ImageButton detailBtn;
        }
    }

    private class FriendsRequestsAdapter extends BaseAdapter{
        private int resource;//数据绑定在哪个资源界面上
        private LayoutInflater inflater;//布局填充器,可以使用xml文件来生成它的view对象
        private FriendInvitationItemViewCache viewCache;

        private FriendsRequestsAdapter(Context context, int resource) {
            this.resource = resource;
            inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }

        @Override
        public int getCount() {
            return friendRequests.size();
        }

        @Override
        public Object getItem(int position) {
            return friendRequests.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        public void removeItem(int position){
            friendRequests.remove(position);
            this.notifyDataSetChanged();
        }
        public void acceptInvitation(FriendRequest friendRequest,int position){
            friends.add(new User(friendRequest.getGuid(),friendRequest.getName()));
            friendsAdapter.notifyDataSetChanged();
            friendRequests.remove(position);
            this.notifyDataSetChanged();
        }
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            TextView nameView;
            ImageButton rejectBtn;
            ImageButton acceptBtn;
            ImageButton detailBtn;
            if(convertView == null){//第一次渲染
                convertView = inflater.inflate(resource,null);
                nameView = (TextView) convertView.findViewById(R.id.myfriend_invitation_name);
                rejectBtn = (ImageButton) convertView.findViewById(R.id.myfriend_invitation_action_reject);
                acceptBtn = (ImageButton) convertView.findViewById(R.id.myfriend_invitation_action_accept);
                detailBtn = (ImageButton) convertView.findViewById(R.id.myfriend_invitation_action_details);
                viewCache = new FriendInvitationItemViewCache();
                viewCache.nameView = nameView;
                viewCache.rejectBtn = rejectBtn;
                viewCache.acceptBtn = acceptBtn;
                viewCache.detailBtn = detailBtn;
            }else{
                nameView = viewCache.nameView;
                rejectBtn = viewCache.rejectBtn;
                acceptBtn = viewCache.acceptBtn;
                detailBtn = viewCache.detailBtn;
            }
            FriendRequest friendRequest = friendRequests.get(position);
            nameView.setText(friendRequest.getName());

            rejectBtn.setOnClickListener(new ButtonListener(position));
            acceptBtn.setOnClickListener(new ButtonListener(position));
            detailBtn.setOnClickListener(new ButtonListener(position));
            return convertView;
        }

        private class ButtonListener implements View.OnClickListener{
            int position;

            private ButtonListener(int position) {
                this.position = position;
            }

            @Override
            public void onClick(View v) {
                int vid = v.getId();
                FriendRequest friendRequest = friendRequests.get(position);
                if(vid == viewCache.rejectBtn.getId()){//click the reject invitation button
                    removeItem(position);
                    //TODO-- call remote server to reject the invitation
                }else if(vid == viewCache.acceptBtn.getId()){//click the accept invitation button
                    acceptInvitation(friendRequest,position);
                    //TODO-- call remote server to accept the inviation
                }else if(vid == viewCache.detailBtn.getId()){
                    //TODO-- call remote server to show the detail information of the user
                    Toast.makeText(getActivity(), "Invitation details:" + friendRequest.getName()+ friendRequest.getGuid(), Toast.LENGTH_SHORT).show();
                }
            }
        }

        private class FriendInvitationItemViewCache{
            public TextView nameView;
            public ImageButton rejectBtn;
            public ImageButton acceptBtn;
            public ImageButton detailBtn;
        }
    }




    private void friendsListRender(final UserToken token){
        new Thread(new Runnable() {
            @Override
            public void run() {
                friendsJson = ServerAccessHelper.queryStringForGet(RemoteUrlCollections.FRIENDS, token.getToken());
                getActivity().runOnUiThread(uiFriendsUpdate);
            }
        }).start();
    }

    private void invitationsListRender(final UserToken token){
        new Thread(new Runnable() {
            @Override
            public void run() {
                friendsRequestsJson = ServerAccessHelper.queryStringForGet(RemoteUrlCollections.FRIENDS_REQUESTS,token.getToken());
                getActivity().runOnUiThread(uiInvitationsUpdate);
            }
        });
    }

    private Runnable uiFriendsUpdate = new Runnable() {
        @Override
        public void run() {
            if(!Constant.RESPONSE_BADLY.equals(friendsJson)){
                try {
                    JSONArray friendsJsonArray = new JSONArray(friendsJson);
                    for(int i=0;i < friendsJsonArray.length(); i++){
                        JSONObject friendObj = friendsJsonArray.getJSONObject(i);
                        String guid = friendObj.getString("guid");
                        String name = friendObj.getString("name");
                        friends.add(new User(guid,name));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
    };

    private Runnable uiInvitationsUpdate  = new Runnable() {
        @Override
        public void run() {
            if(!Constant.RESPONSE_BADLY.equals(friendsRequestsJson)){
                try {
                    JSONArray requestsArray = new JSONArray();
                    for(int i=0; i < requestsArray.length(); i++){
                        JSONObject requsetObj = requestsArray.getJSONObject(i);
                        String guid = requsetObj.getString("guid");
                        String name = requsetObj.getString("name");
                        String userGuid = requsetObj.getString("userGuid");
                        friendRequests.add(new FriendRequest(guid,name,userGuid));
                    }
                }catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
    };



    private class FriendRequest{
        private String guid;
        private String name;
        private String userGuid;

        public FriendRequest(String guid, String name, String userGuid) {
            this.guid = guid;
            this.name = name;
            this.userGuid = userGuid;
        }

        public String getGuid() {
            return guid;
        }

        public String getName() {
            return name;
        }

        public String getUserGuid() {
            return userGuid;
        }
    }
}
